package com.glsc.ngateway.common.base.repo.mysql.gateway.platform;

import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.Role;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.List;

@Repository
public interface RoleRepo extends JpaRepository<Role, Long>, JpaSpecificationExecutor<Role> {
    //@Lock(value = LockModeType.PESSIMISTIC_WRITE)
    @Query(value = "select r from Role r where r.id = :id and r.deleted = 0")
    Role queryByIdLock(@Param("id") long id);

    @Query(value = "select r from Role r where r.name = :name and r.deleted = 0")
    List<Role> queryByName(@Param("name") String name);

    @Transactional
    @Modifying
    @Query(value = "delete from Role r where r.id = :id")
    int deleteById(@Param("id") long id);

    @Query(value="select * from t_role r join t_role_url ru on r.id=ru.role_id where ru.url_id = :authId "+
            "and if( :#{#name} is not null, r.name like CONCAT('%', :#{#name}, '%'), 1=1 ) "
            , nativeQuery = true)
    Page<Role> page(Pageable pageable, @NotNull @Param("authId") long authId, @Param("name") String name);

    List<Role> findAllByNameIn(List<String> roleNameList);

    @Query(value = "select * from t_role r join t_user_role u on r.id = u.role_id where u.user_id in :userIds", nativeQuery = true)
    List<Role> findAllByUserIdIn(@Param("userIds") List<Long> userIds);

}
